<template>
  <div class="app-container">
    <h2 class="title">{{ bankName }}题库详情页面</h2>
    <div class="filter-and-buttons-container">
      <!-- 筛选条件部分 -->
      <div class="filter-container">
        <span>试题分类:</span>
        <el-select v-model="selectedCategory" placeholder="请选择">
          <el-option label="分类1" value="category1"></el-option>
          <el-option label="分类2" value="category2"></el-option>
          <!-- 可根据实际情况添加更多选项 -->
        </el-select>
        <span>题型:</span>
        <el-select v-model="selectedType" placeholder="请选择">
          <el-option label="单选题" value="0"></el-option>
          <el-option label="多选题" value="1"></el-option>
          <el-option label="简答题" value="2"></el-option>
          <!-- 可根据实际情况添加更多选项 -->
        </el-select>
        <span>难度:</span>
        <el-select v-model="selectedDifficulty" placeholder="请选择">
          <el-option label="不限难度" value="3"></el-option>
          <el-option label="简单" value="0"></el-option>
          <el-option label="中等" value="1"></el-option>
          <el-option label="困难" value="2"></el-option>
          <!-- 可根据实际情况添加更多选项 -->
        </el-select>
        <el-button type="primary" @click="queryQuestions">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>
      <!-- 功能按钮部分 -->
      <div class="function-buttons">
        <el-button type="primary" @click="openAddDialog">新增试题</el-button>
        <el-button type="primary" @click="handleTemplateImport">模板导入</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>
    </div>
    <!-- 表格展示数据部分 -->
    <el-table :data="questionList" border style="width: 100%">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="试题分类" prop="questionCategory"></el-table-column>
      <el-table-column label="题型">
        <template slot-scope="scope">
          {{ getQuestionTypeText(scope.row.questionType) }}
        </template>
      </el-table-column>
      <el-table-column label="题干" prop="questionContent"></el-table-column>
      <el-table-column label="正确答案" prop="correctAnswer"></el-table-column>
      <el-table-column label="难度">
        <template slot-scope="scope">
          {{ getDifficultyText(scope.row.difficulty) }}
        </template>
      </el-table-column>
      <el-table-column label="创建日期" prop="createDate"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加试题的弹窗 -->
    <el-dialog title="添加试题" :visible.sync="addDialogVisible" width="400px">
      <el-form :model="newQuestion" label-width="80px">
        <el-form-item label="试题分类">
          <el-select v-model="newQuestion.questionCategory" placeholder="请选择">
            <el-option label="分类1" value="category1"></el-option>
            <el-option label="分类2" value="category2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-select v-model="newQuestion.questionType" placeholder="请选择">
            <el-option label="单选题" value="0"></el-option>
            <el-option label="多选题" value="1"></el-option>
            <el-option label="简答题" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题干">
          <el-input v-model="newQuestion.questionContent" placeholder="请输入题干"></el-input>
        </el-form-item>
        <template v-if="newQuestion.questionType === '0' || newQuestion.questionType === '1'">
          <el-form-item label="选项A">
            <el-input v-model="newQuestion.optionA" placeholder="请输入内容"></el-input>
            <template v-if="newQuestion.questionType === '0'">
              <el-radio v-model="newQuestion.correctAnswer" :label="'A'">设为正确答案</el-radio>
            </template>
            <template v-if="newQuestion.questionType === '1'">
              <el-checkbox v-model="newQuestion.correctAnswerArr" :label="'A'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="选项B">
            <el-input v-model="newQuestion.optionB" placeholder="请输入内容"></el-input>
            <template v-if="newQuestion.questionType === '0'">
              <el-radio v-model="newQuestion.correctAnswer" :label="'B'">设为正确答案</el-radio>
            </template>
            <template v-if="newQuestion.questionType === '1'">
              <el-checkbox v-model="newQuestion.correctAnswerArr" :label="'B'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="选项C">
            <el-input v-model="newQuestion.optionC" placeholder="请输入内容"></el-input>
            <template v-if="newQuestion.questionType === '0'">
              <el-radio v-model="newQuestion.correctAnswer" :label="'C'">设为正确答案</el-radio>
            </template>
            <template v-if="newQuestion.questionType === '1'">
              <el-checkbox v-model="newQuestion.correctAnswerArr" :label="'C'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="选项D">
            <el-input v-model="newQuestion.optionD" placeholder="请输入内容"></el-input>
            <template v-if="newQuestion.questionType === '0'">
              <el-radio v-model="newQuestion.correctAnswer" :label="'D'">设为正确答案</el-radio>
            </template>
            <template v-if="newQuestion.questionType === '1'">
              <el-checkbox v-model="newQuestion.correctAnswerArr" :label="'D'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="解析">
            <el-input v-model="newQuestion.analysis" placeholder="请输入内容"></el-input>
          </el-form-item>
        </template>
        <template v-if="newQuestion.questionType === '2'">
          <el-form-item label="答案">
            <el-input v-model="newQuestion.correctAnswer" placeholder="请输入答案"></el-input>
          </el-form-item>
          <el-form-item label="解析">
            <el-input v-model="newQuestion.analysis" placeholder="请输入内容"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="难度">
          <el-select v-model="newQuestion.difficulty" placeholder="请选择">
            <el-option label="不限难度" value="3"></el-option>
            <el-option label="简单" value="0"></el-option>
            <el-option label="中等" value="1"></el-option>
            <el-option label="困难" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addQuestionSubmit">确定</el-button>
      </div>
    </el-dialog>
    <!-- 修改试题的弹窗 -->
    <el-dialog title="修改试题" :visible.sync="editDialogVisible" width="400px">
      <el-form :model="editedQuestion" label-width="80px">
        <el-form-item label="试题分类">
          <el-select v-model="editedQuestion.questionCategory" placeholder="请选择">
            <el-option label="分类1" value="category1"></el-option>
            <el-option label="分类2" value="category2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-select v-model="editedQuestion.questionType" placeholder="请选择">
            <el-option label="单选题" value="0"></el-option>
            <el-option label="多选题" value="1"></el-option>
            <el-option label="简答题" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题干">
          <el-input v-model="editedQuestion.questionContent" placeholder="请输入题干"></el-input>
        </el-form-item>
        <template v-if="editedQuestion.questionType === '0' || editedQuestion.questionType === '1'">
          <el-form-item label="选项A">
            <el-input v-model="editedQuestion.optionA" placeholder="请输入内容"></el-input>
            <template v-if="editedQuestion.questionType === '0'">
              <el-radio v-model="editedQuestion.correctAnswer" :label="'A'">设为正确答案</el-radio>
            </template>
            <template v-if="editedQuestion.questionType === '1'">
              <el-checkbox v-model="editedQuestion.correctAnswerArr" :label="'A'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="选项B">
            <el-input v-model="editedQuestion.optionB" placeholder="请输入内容"></el-input>
            <template v-if="editedQuestion.questionType === '0'">
              <el-radio v-model="editedQuestion.correctAnswer" :label="'B'">设为正确答案</el-radio>
            </template>
            <template v-if="editedQuestion.questionType === '1'">
              <el-checkbox v-model="editedQuestion.correctAnswerArr" :label="'B'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="选项C">
            <el-input v-model="editedQuestion.optionC" placeholder="请输入内容"></el-input>
            <template v-if="editedQuestion.questionType === '0'">
              <el-radio v-model="editedQuestion.correctAnswer" :label="'C'">设为正确答案</el-radio>
            </template>
            <template v-if="editedQuestion.questionType === '1'">
              <el-checkbox v-model="editedQuestion.correctAnswerArr" :label="'C'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="选项D">
            <el-input v-model="editedQuestion.optionD" placeholder="请输入内容"></el-input>
            <template v-if="editedQuestion.questionType === '0'">
              <el-radio v-model="editedQuestion.correctAnswer" :label="'D'">设为正确答案</el-radio>
            </template>
            <template v-if="editedQuestion.questionType === '1'">
              <el-checkbox v-model="editedQuestion.correctAnswerArr" :label="'D'">设为正确答案</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="解析">
            <el-input v-model="editedQuestion.analysis" placeholder="请输入内容"></el-input>
          </el-form-item>
        </template>
        <template v-if="editedQuestion.questionType === '2'">
          <el-form-item label="答案">
            <el-input v-model="editedQuestion.correctAnswer" placeholder="请输入答案"></el-input>
          </el-form-item>
          <el-form-item label="解析">
            <el-input v-model="editedQuestion.analysis" placeholder="请输入内容"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="难度">
          <el-select v-model="editedQuestion.difficulty" placeholder="请选择">
            <el-option label="不限难度" value="3"></el-option>
            <el-option label="简单" value="0"></el-option>
            <el-option label="中等" value="1"></el-option>
            <el-option label="困难" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editQuestionSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 从封装的 API 文件中引入相关函数
import {
  listQuestion,
  listQuestion_bank,
  queryQuestionsByCondition,
  addQuestion,
  updateQuestion,
  deleteQuestion,
  batchDeleteQuestion
} from "@/api/question_bank/QuestionDetail";

export default {
  name: "QuestionDetail",
  data() {
    return {
      bankId: null, // 动态路由参数
      queryBankId: null, // 查询参数
      bankName: "",
      selectedCategory: "", // 选中的试题分类
      selectedType: "", // 选中的题型
      selectedDifficulty: "", // 选中的难度
      questionList: [], // 用于存储获取到的试题数据
      addDialogVisible: false, // 控制添加弹窗的显示与隐藏
      newQuestion: {
        questionCategory: "",
        questionType: "",
        questionContent: "",
        correctAnswer: "",
        difficulty: "",
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        analysis: "",
        correctAnswerArr: []
      }, // 用于存储新试题的信息
      editDialogVisible: false, // 控制修改弹窗的显示与隐藏
      editedQuestion: {
        questionCategory: "",
        questionType: "",
        questionContent: "",
        correctAnswer: "",
        difficulty: "",
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        analysis: "",
        correctAnswerArr: []
      }, // 用于存储待修改的试题信息
      currentEditedRow: null // 当前要修改的行数据
    };
  },
  created() {
    // 获取动态路由参数
    this.bankId = this.$route.params.bankId;
    // 获取查询参数
    this.queryBankId = this.$route.query.bankId;
    // 调用获取试题列表和题库名称的方法
    this.findList();
    this.findQuestionList();
  },
  methods: {
    // 获取试题列表的方法
    findList() {
      listQuestion(this.bankId)
        .then((res) => {
          // 假设接口返回的是包含试题信息的数组
          if (Array.isArray(res)) {
            this.questionList = res;
            console.log(res);
          } else {
            console.error('接口返回数据格式错误，不是数组');
          }
        })
        .catch((error) => {
          console.error('获取试题列表失败:', error);
        });
    },
    // 获取题库名称的方法
    findQuestionList() {
      listQuestion_bank(this.bankId)
        .then((res) => {
          this.bankName = res;
          console.log(res);
        })
        .catch((error) => {
          console.error('查询题库列表失败:', error);
        });
    },
    // 根据筛选条件查询试题的方法
    queryQuestions() {
      const params = {
        bankId: this.bankId,
        category: this.selectedCategory,
        type: this.selectedType,
        difficulty: this.selectedDifficulty
      };
      queryQuestionsByCondition(params)
        .then((res) => {
          if (Array.isArray(res)) {
            this.questionList = res;
            console.log('查询成功，获取到的试题列表：', res);
          } else {
            console.error('查询接口返回数据格式错误，不是数组');
          }
        })
        .catch((error) => {
          console.error('查询试题失败:', error);
        });
    },
    // 重置筛选条件的方法
    resetFilters() {
      // 重置选择框的值
      this.selectedCategory = "";
      this.selectedType = "";
      this.selectedDifficulty = "";
    },
    // 打开新增试题弹窗的方法
    openAddDialog() {
      this.addDialogVisible = true;
      // 重置新试题信息
      this.newQuestion = {
        questionCategory: "",
        questionType: "",
        questionContent: "",
        correctAnswer: "",
        difficulty: "",
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        analysis: "",
        correctAnswerArr: []
      };
    },
    // 提交新增试题的方法
    addQuestionSubmit() {
      // 处理单选题和多选题的正确答案格式
      if (this.newQuestion.questionType === '0') {
        this.newQuestion.correctAnswerArr = [this.newQuestion.correctAnswer];
      } else if (this.newQuestion.questionType === '1') {
        this.newQuestion.correctAnswer = this.newQuestion.correctAnswerArr.join('');
      }
      // 构造要发送到后端的数据
      const questionData = {
        bankId: this.bankId, // 假设后端需要题库ID
        questionCategory: this.newQuestion.questionCategory,
        questionType: this.newQuestion.questionType,
        questionContent: this.newQuestion.questionContent,
        correctAnswer: this.newQuestion.correctAnswer,
        difficulty: this.newQuestion.difficulty,
        optionA: this.newQuestion.optionA,
        optionB: this.newQuestion.optionB,
        optionC: this.newQuestion.optionC,
        optionD: this.newQuestion.optionD,
        analysis: this.newQuestion.analysis
      };
      // 调用若依API
      addQuestion(questionData)
        .then((response) => {
          if (response.data.code === 200) {
            console.log('新增试题成功');
            // 关闭弹窗
            this.addDialogVisible = false;
            // 刷新试题列表
            this.findList();
          } else {
            console.error('新增试题失败：', response.data.msg);
          }
        })
        .catch((error) => {
          console.error('新增试题请求出错：', error);
        });
    },
    // 处理编辑试题的方法
    handleEdit(row) {
      this.currentEditedRow = row;
      // 将当前行数据复制到 editedQuestion 中
      this.editedQuestion = {
        ...row
      };
      // 处理多选题答案到数组形式
      if (row.questionType === '1') {
        this.editedQuestion.correctAnswerArr = row.correctAnswer.split('');
      } else {
        this.editedQuestion.correctAnswerArr = [row.correctAnswer];
      }
      this.editDialogVisible = true;
    },
    // 提交修改试题的方法
    editQuestionSubmit() {
      // 处理单选题和多选题的正确答案格式
      if (this.editedQuestion.questionType === '0') {
        this.editedQuestion.correctAnswerArr = [this.editedQuestion.correctAnswer];
      } else if (this.editedQuestion.questionType === '1') {
        this.editedQuestion.correctAnswer = this.editedQuestion.correctAnswerArr.join('');
      }
      // 构造要发送到后端的数据
      const editQuestionData = {
        questionId: this.editedQuestion.id, // 假设后端需要试题ID来更新
        questionCategory: this.editedQuestion.questionCategory,
        questionType: this.editedQuestion.questionType,
        questionContent: this.editedQuestion.questionContent,
        correctAnswer: this.editedQuestion.correctAnswer,
        difficulty: this.editedQuestion.difficulty,
        optionA: this.editedQuestion.optionA,
        optionB: this.editedQuestion.optionB,
        optionC: this.editedQuestion.optionC,
        optionD: this.editedQuestion.optionD,
        analysis: this.editedQuestion.analysis
      };
      // 调用若依API
      updateQuestion(editQuestionData)
        .then((response) => {
          if (response.data.code === 200) {
            console.log('修改试题成功');
            // 关闭弹窗
            this.editDialogVisible = false;
            // 刷新试题列表
            this.findList();
          } else {
            console.error('修改试题失败：', response.data.msg);
          }
        })
        .catch((error) => {
          console.error('修改试题请求出错：', error);
        });
    },
    // 处理删除试题的方法
    handleDelete(row) {
      const params = {
        questionId: row.id // 假设后端接口需要试题的id来删除，这里根据实际情况修改
      };
      // 调用若依API
      deleteQuestion(params)
        .then((response) => {
          if (response.data.code === 200) {
            console.log('删除试题成功');
            // 从列表中移除该试题
            const index = this.questionList.indexOf(row);
            if (index > -1) {
              this.questionList.splice(index, 1);
            }
          } else {
            console.error('删除试题失败：', response.data.msg);
          }
        })
        .catch((error) => {
          console.error('删除试题请求出错：', error);
        });
    },
    // 处理模板导入的方法（暂时仅打印日志，后续需完善）
    handleTemplateImport() {
      console.log('点击了模板导入按钮');
      // 后续需添加实际的模板导入逻辑，例如打开文件选择框等
    },
    // 处理批量删除试题的方法
    handleBatchDelete() {
      console.log('点击了批量删除按钮');
      // 这里获取选中的行数据，假设el-table的selection是选中的行
      const selectedRows = this.$refs.questionTable.selection;
      const ids = selectedRows.map(row => row.id); // 假设后端接口需要id数组来批量删除，根据实际情况修改
      const batchParams = {
        ids: ids
      };
      // 调用若依API
      batchDeleteQuestion(batchParams)
        .then((response) => {
          if (response.data.code === 200) {
            console.log('批量删除试题成功');
            // 刷新试题列表
            this.findList();
          } else {
            console.error('批量删除试题失败：', response.data.msg);
          }
        })
        .catch((error) => {
          console.error('批量删除试题请求出错：', error);
        });
    },
    // 获取题型文本的方法
    getQuestionTypeText(type) {
      const typeMap = {
        '0': '单选题',
        '1': '多选题',
        '2': '简答题'
      };
      return typeMap[type] || '未知题型';
    },
    // 获取难度文本的方法
    getDifficultyText(difficulty) {
      const difficultyMap = {
        '0': '简单',
        '1': '中等',
        '2': '困难',
        '3': '不限难度'
      };
      return difficultyMap[difficulty] || '未知难度';
    }
  }
};
</script>
